import { createContext, useState, useEffect } from'react';
import { Outlet, useNavigate } from'react-router-dom';
import { Tabbar } from '@nutui/nutui-react'
import { Home, Find, Mail, User } from '@nutui/icons-react'
export const WebSocketContext = createContext();
// Get user ID from local storage
let use_id = (JSON.parse(localStorage.getItem('use')) || {}). _id;
let friend_messages=localStorage.getItem('friend_messages') || '[]';
friend_messages=JSON.parse(friend_messages);
export default function App() {
  const navigate = useNavigate();
  const [ws, setWs] = useState(null); // Use state to store WebSocket instance
  const [messages, setMessages] = useState([]);
  let startWebSocket = () => {
    if (!use_id) {
      return;
    }
    const websocket = new WebSocket(`ws://localhost:8080?id=${use_id}`);
    
    websocket.onopen = () => {
      console.log('服务器连接成功');
    };
    
    websocket.onmessage = (event) => {
      let data = JSON.parse(event.data);
      friend_messages.forEach(item=>{
        if(item==data.accepted_id){
            localStorage.setItem('friend_messages',JSON.stringify({[item]:data.send_name}))
        }
      })
      setMessages((prevMessages) => [...prevMessages, JSON.parse(event.data)]);
    };
    
    websocket.onclose = () => {
      console.log('服务器关闭');
    };
    
    websocket.onerror = (error) => {
      console.log('异常', error);
    };
    
    setWs(websocket); 
  };
  
  useEffect(() => {
    startWebSocket();
    return () => {
      if (ws) {
        ws.close(); 
      }
    };
  }, []); 

  return (
    <div>
      <WebSocketContext.Provider value={{ws,messages}}>  {/* Pass WebSocket instance */}
        <Outlet />
        </WebSocketContext.Provider>
      <Tabbar defaultValue={0}
        fixed
        onSwitch={(e) => {
          if (e == 0) {
            navigate('/home')
          }
          if (e == 1) {
            navigate('/cate')
          }
          if(e==2){
            navigate('/message')
          }
          if(e==3){
            navigate('/my')
          }
        }} 
        style={{ height: '70px' }}
      >
        <Tabbar.Item
          icon={<Home width={30} height={30} />}
        />
        <Tabbar.Item icon={<Find width={30} height={30} />} />
        <Tabbar.Item icon={<Mail width={30} height={30} />} />
        <Tabbar.Item icon={<User width={30} height={30} />} />
      </Tabbar>
    </div>
  );
}
